import { DecoratorNode, type EditorConfig, type NodeKey, type LexicalNode } from 'lexical'

export class VariableNode extends DecoratorNode<HTMLSpanElement> {
  __variable: string

  static getType(): string {
    return 'variable'
  }

  static clone(node: VariableNode): VariableNode {
    return new VariableNode(node.__variable, node.__key)
  }

  constructor(variable: string, key?: NodeKey) {
    super(key)
    this.__variable = variable
  }

  createDOM(config: EditorConfig): HTMLElement {
    const dom = document.createElement('span')
    dom.style.color = '#7839EE'
    dom.className = 'variable'
    dom.textContent = `{{${this.__variable}}}`
    return dom
  }

  updateDOM(): boolean {
    return false
  }

  decorate(): HTMLSpanElement {
    const span = document.createElement('span')
    span.className = 'variable'
    span.textContent = `{{${this.__variable}}}`
    return span
  }

  isInline(): boolean {
    return true
  }
}

export function $createVariableNode(variable: string): VariableNode {
  return new VariableNode(variable)
}

export function $isVariableNode(node: LexicalNode | null | undefined): node is VariableNode {
  return node instanceof VariableNode
}
